import { useState, useEffect } from 'react';
import { FaPaintBrush } from 'react-icons/fa';

const FormatPainter = ({ quill }) => {
  const [isActive, setIsActive] = useState(false);
  const [storedFormat, setStoredFormat] = useState(null);

  const handleFormatPainter = () => {
    if (!quill) return;

    if (!isActive) {
      // 获取当前选中文本的格式
      const range = quill.getSelection();
      if (range && range.length > 0) {
        const formats = quill.getFormat(range);
        setStoredFormat(formats);
        setIsActive(true);
      }
    } else {
      // 取消格式刷
      setIsActive(false);
      setStoredFormat(null);
    }
  };

  // 应用格式到新选区
  const applyFormat = (range) => {
    if (range && range.length > 0) {
      if (storedFormat && Object.keys(storedFormat).length > 0) {
        // 应用存储的格式
        Object.entries(storedFormat).forEach(([format, value]) => {
          quill.formatText(range.index, range.length, format, value, 'user');
        });
      } else {
        // 清除格式
        quill.removeFormat(range.index, range.length, 'user');
      }
      // 应用后自动关闭格式刷
      setIsActive(false);
      setStoredFormat(null);
    }
  };

  // 使用 useEffect 监听选择变化
  useEffect(() => {
    if (!quill || !isActive) return;

    const handleSelectionChange = (range) => {
      if (range && range.length > 0) {
        applyFormat(range);
      }
    };

    quill.on('selection-change', handleSelectionChange);

    // 清理函数
    return () => {
      quill.off('selection-change', handleSelectionChange);
    };
  }, [quill, isActive, storedFormat]);

  // 点击编辑器空白处时取消格式刷
  useEffect(() => {
    if (!quill || !isActive) return;

    const handleClick = () => {
      if (!quill.getSelection()) {
        setIsActive(false);
        setStoredFormat(null);
      }
    };

    document.addEventListener('click', handleClick);

    return () => {
      document.removeEventListener('click', handleClick);
    };
  }, [quill, isActive]);

  return (
    <button 
      className={`format-painter-btn ${isActive ? 'active' : ''}`}
      onClick={(e) => {
        e.stopPropagation(); // 阻止事件冒泡
        handleFormatPainter();
      }}
      title="格式刷"
    >
      <FaPaintBrush /> 格式刷
    </button>
  );
};

export default FormatPainter;